/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ebe.dao;

import ebe.model.Usuario;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Ramayane
 */
public class UsuarioDAO {

    public Usuario pegaUsuarioPeloCPF(DB db, String cpf) throws SQLException {
        Usuario u = null;
        PreparedStatement usr = db.sql("select * from usuario where cpf=?");
        usr.setString(1, cpf);
        ResultSet rs = usr.executeQuery();
        if (rs.next()) {
            u = le(rs);
        }
        rs.close();
        usr.close();
        return u;
    }

    private Usuario le(ResultSet rs) throws SQLException {
        Usuario u = new Usuario(rs.getString("cpf"), rs.getString("senha"), rs.getString("nome"),
                rs.getDate("data_nasc"), rs.getString("sexo"),
                rs.getString("escolaridade"), rs.getString("estado"), rs.getString("cidade"), rs.getString("endereco_compl"),
                rs.getString("email"), rs.getString("descricao"), rs.getBytes("foto"));
        return u;
    }

    public void salvar(DB db, Usuario usu) throws SQLException {
        PreparedStatement c = db.sql("insert into usuario(cpf, nome, email, senha, data_nasc,"
                + "sexo, escolaridade, estado, cidade, endereco_compl, descricao, foto)"
                + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        c.setString(1, usu.getCpf());
        c.setString(2, usu.getNome());
        c.setString(3, usu.getEmail());
        c.setString(4, usu.getSenha());
        c.setDate(5, usu.getData_nasc());
        c.setString(6, usu.getSexo());
        c.setString(7, usu.getEscolaridade());
        c.setString(8, usu.getEstado());
        c.setString(9, usu.getCidade());
        c.setString(10, usu.getEndereco_compl());
        c.setString(11, usu.getDescricao());
        c.setBytes(12, usu.getFoto());
        c.executeUpdate();
    }

    public void gravaImagem(Usuario usu, HttpServletRequest request) {

        usu.setFoto(pegaFoto(request));
        try {
            DB db = new DB();
            PreparedStatement c = db.sql("update usuario set foto=? where cpf=?");
            c.setBytes(1, usu.getFoto());
            c.setString(2, usu.getCpf());
            c.executeUpdate();
            db.close();
        } catch (SQLException ex) {
        }
    }

    public void atualizar(DB db, Usuario usu) throws SQLException {
        PreparedStatement c = db.sql("update usuario set nome=?, email=?, senha=?, data_nasc=?,"
                + "sexo=?, escolaridade=?, estado=?, cidade=?, endereco_compl=?, descricao=?, foto=?"
                + " where cpf=?");
        c.setString(1, usu.getNome());
        c.setString(2, usu.getEmail());
        c.setString(3, usu.getSenha());
        c.setDate(4, usu.getData_nasc());
        c.setString(5, usu.getSexo());
        c.setString(6, usu.getEscolaridade());
        c.setString(7, usu.getEstado());
        c.setString(8, usu.getCidade());
        c.setString(9, usu.getEndereco_compl());
        c.setString(10, usu.getDescricao());
        c.setBytes(11, usu.getFoto());
        c.setString(12, usu.getCpf());
        c.executeUpdate();
    }

    public void excluir(DB db, Usuario usuario) throws SQLException {
        PreparedStatement c = db.sql("delete from usuario where cpf=?");
        c.setString(1, usuario.getCpf());
        c.executeUpdate();
    }

    private byte[] pegaFoto(HttpServletRequest request) {

        DiskFileItemFactory fileUpload = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(fileUpload);
        if (request.getContentType() == null) {
            return null;
        }

        if (!request.getContentType().startsWith("multipart/form-data")) {
            return null;
        }

        fileUpload.setSizeThreshold(4096);

        try {
            sfu.setSizeMax(20 * 1024 * 1024);

            List list = sfu.parseRequest(request);


            for (Iterator iterator = list.iterator(); iterator.hasNext();) {
                FileItem item = (FileItem) iterator.next();

                if (!item.isFormField()) {
                    String filename = item.getName();


                    if ((filename != null) && (!filename.equals(""))) {
                        filename = (new File(filename)).getName();
                        InputStream in = item.getInputStream();
                        int tamnho = in.available();
                        byte[] imagem = new byte[tamnho];
                        in.read(imagem);
                        return imagem;
                    }

                }
            }

        } catch (Exception slee) {
            slee.printStackTrace();
        }

        return null;
    }
}
